#!/usr/bin/env bash

IMAGE_NAME=bitnami/zookeeper
VERSION=3.8.2
PORT=2181
SERVER_NAME=zookeeper
DIR=/home/app/kafka/$SERVER_NAME

if [ -d "./Dockerfile" ]; then
  echo "Find Dockerfile.Will build docker images."
  docker build -t $IMAGE_NAME:$VERSION ./
fi

if [ ! -d "$DIR" ]; then
  mkdir -p $DIR;
  echo "dir $DIR create successful."
else
  echo "dir $DIR already exist.Will use it."
fi

echo "remove old container"

EM_RUN=$(docker ps| grep $IMAGE_NAME|awk 'NR==1'|awk '{print $1}')
EM=$(docker ps -a | grep $IMAGE_NAME|awk 'NR==1'|awk '{print $1}')

if [ -n "$EM_RUN" ]; then
  echo "container $EM_RUN is running.will stop and delete it."
  docker stop "$EM_RUN"
  docker rm "$EM_RUN"
elif [ -n "$EM" ]; then
  echo "container $EM is stop,but container is exists,will only delete it."
  docker rm "$EM"
else
  echo "Not find container $IMAGE_NAME"
fi
#0x17D78400
echo "run new container"
docker run --name "$SERVER_NAME" -d \
-p $PORT:$PORT \
-e ZOO_ENABLE_AUTH=yes \
-e SERVER_JVMFLAGS="-Djava.security.auth.login.config=/opt/bitnami/zookeeper/conf/server_jaas.conf
-Dzookeeper.serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
-Dzookeeper.ssl.keyStore.location=/opt/bitnami/zookeeper/conf/kafka.keystore.jks
-Dzookeeper.ssl.keyStore.password=kafka123
-Dzookeeper.ssl.trustStore.location=/opt/bitnami/zookeeper/conf/kafka.truststore.jks
-Dzookeeper.ssl.trustStore.password=kafka123
-Djute.maxbuffer=0x400000" \
-v $DIR/conf/server_jaas.conf:/opt/bitnami/zookeeper/conf/server_jaas.conf \
-v $DIR/conf/server.keystore.jks:/opt/bitnami/zookeeper/conf/kafka.keystore.jks \
-v $DIR/conf/server.truststore.jks:/opt/bitnami/zookeeper/conf/kafka.truststore.jks \
--restart=always $IMAGE_NAME:$VERSION